/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package student;

import common.MessageModel;
import common.Message_Type;
import java.io.BufferedInputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextArea;

/**
 *
 * @author Eugene-Forest
 */
public class ReceiveNoticeThread extends Thread {

    private Socket socket;
    private JDialog noticeDialog;
    private JTextArea noticeArea;
    private JButton noticeButton;
    private JLabel publishLabel;
    private ObjectInputStream in;
    private JTextArea message_panel;

    public ReceiveNoticeThread(Socket socket, JDialog noticeDialog,
            JTextArea noticeArea, JButton noticeButton, JLabel publishLabel, JTextArea message_panel) {
        this.socket = socket;
        this.noticeDialog = noticeDialog;
        this.noticeArea = noticeArea;
        this.noticeButton = noticeButton;
        this.publishLabel = publishLabel;
        this.message_panel = message_panel;
    }

    @Override
    public void run() {
        try {
            //事先定义一个bufferedInputStream对象转换InputStream对象以减少频繁创建ObjectInputStream时造成的资源浪费
            BufferedInputStream bis=new BufferedInputStream(socket.getInputStream());
            while (true) {
                in = new ObjectInputStream(bis);
                MessageModel messageModel = (MessageModel) in.readObject();
                //判断是否是通知
                if (messageModel != null) {
                    if (messageModel.getType() == Message_Type.Notice) {
                        //判断是否是实时通知
                        if (messageModel.isReal_time()) {
                            //如果为真，说明有一则实时公告发布，消除对上一次公告的记录
                            StudentSide.read_notice=false;
                            StudentSide.auto_code=messageModel.get_auth_code();
                            //向公告窗口填充公告信息并显示
                            noticeArea.setText(messageModel.getMessageString());
                            publishLabel.setText(messageModel.getPublishDate());
                            noticeDialog.setVisible(true);
                        }
                        //无论是否是实时公告，都需要写入历史公告板中
                        message_panel.append(messageModel.getPublishDate() + ":\n"
                                + messageModel.getMessageString() + "\n");
                        message_panel.append("----------\n\n");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
